from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
import requests
from bs4 import BeautifulSoup
import json


#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data

def formData(response):
    allData = []
    # 获取sid并且更新返回
    soup = BeautifulSoup(response.text, "html5lib")

    lis = soup.select("#hitlist ol .result-add-remove")

    for li in lis:
        tempData = resultData()

        try:
            tempData["titleName"] = li.select("h3 a")[0].text.strip()
        except:
            pass
        try:
            tempData["titleHref"] = 'https://science-of-synthesis.thieme.com'+li.select("h3 a")[0]["href"]
        except:
            pass
        try:
            auther = li.select("h4")[1].select('.cbau')
            for au in auther:
                tempData["author"].append(au.text.strip())
        except:
            pass
        try:
            tempData["source"] = li.select("h4")[1].text.strip().split(':')[1]
        except:
            pass
        try:
            tempData["summary"] = li.select(".snippet")[0].text.strip()
        except:
            pass
        allData.append(tempData)

    return allData

def getData(keyword):
    headers = {
        'Connection': 'keep-alive',
        'Pragma': 'no-cache',
        'Cache-Control': 'no-cache',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
        'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'Referer': 'https://science-of-synthesis.thieme.com/app/search/results?query=cell&query_rosdal=',
    }


    response = requests.get('https://science-of-synthesis.thieme.com/app/search/results?query='+keyword+'&query_rosdal=', headers=headers)

    allData = formData(response)

    return allData


def index(request):


    # page = 1
    data = json.loads(request.POST.get('data', '1'))

    allData= getData(data["values"][0])

    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")